package com.yl.androidutilscenter.dialog

import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.animation.Animation
import android.view.animation.LinearInterpolator
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.yl.androidutilscenter.R
import com.yl.androidutilscenter.utils.LogUtils
import com.yl.androidutilscenter.utils.YScreenUtils

/**
 * @author
 * @description:
 * @date :2024/3/29
 * @version 1.0.0
 */
class LoadingDialog(mContext: Context, private val tip: String?) : AlertDialog(mContext) {
    private var tvTitle: TextView? = null
    private var ivLoading: ImageView? = null
    private val animation by lazy {
        RotateAnimation(
            0f,
            360f,
            Animation.RELATIVE_TO_SELF,
            0.5f,
            Animation.RELATIVE_TO_SELF,
            0.5f
        )
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setCancelable(false)
        val view = LayoutInflater.from(context).inflate(R.layout.dialog_loading_layout, null)
        setContentView(view)

        this.window?.setBackgroundDrawableResource(R.drawable.shape_loading_ios_bg)
        val layoutParams = this.window?.attributes
        var width = YScreenUtils.getScreenWidth()
        width = if (width > 720) {
            width * 1 / 3
        }else{
            300
        }
        layoutParams?.width = width
        layoutParams?.height = width
        this.window?.attributes = layoutParams


        tvTitle = view.findViewById(R.id.tv_text)
        ivLoading = view.findViewById(R.id.iv_loading)
        tip?.let {
            tvTitle?.text = it
        }

        animation.duration = 2000
        animation.repeatCount = Animation.INFINITE
        animation.interpolator = LinearInterpolator()
        animation.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation?) {
                LogUtils.i("loadingDialog onAnimationStart")
            }

            override fun onAnimationEnd(animation: Animation?) {
                LogUtils.i("loadingDialog onAnimationEnd")
            }

            override fun onAnimationRepeat(animation: Animation?) {
                LogUtils.i("loadingDialog  onAnimationRepeat")
            }

        })
    }

    fun setTip(tip: String) {
        tvTitle?.text = tip
    }

    fun startAnimation() {
        ivLoading?.startAnimation(animation)
    }

    override fun setOnShowListener(listener: DialogInterface.OnShowListener?) {
        super.setOnShowListener(listener)
    }
}